//
//  MovieListViewController.m
//  豆瓣2
//
//  Created by dllo on 15/12/18.
//  Copyright © 2015年 dllo. All rights reserved.
//

#import "MovieListViewController.h"
#import "MovieListTableViewCell.h"
#import "MovieDataViewController.h"
#import "AppTools.h"
#import "Movie.h"
#import "DataBaseSingleton.h"
#import "MJRefresh.h"
#define CELL @"cell"
@interface MovieListViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchResultsUpdating>


@property (nonatomic ,retain)NSMutableArray *array;
@end

@implementation MovieListViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor redColor];
    self.myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)style:UITableViewStylePlain];
    self.myTableView.backgroundColor = [UIColor whiteColor];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    // 注册
//    [self.myTableView registerClass:[MovieListTableViewCell class] forCellReuseIdentifier:CELL];
    [self.view addSubview:self.myTableView];
    // title
    self.navigationItem.title = @"电影";
     self.allArray = [NSMutableArray array];

   
    self.searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    self.searchController.dimsBackgroundDuringPresentation = NO;
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
    [self.searchController.searchBar sizeToFit];
    self.myTableView.tableHeaderView = self.searchController.searchBar;
    self.isUpLoading = NO;
    [self addHeader];
    [self addFooter];
    
}

-(void)addHeader{
 
    __block MovieListViewController *vc = self;
    
    [self.myTableView addHeaderWithCallback:^{
        vc.isUpLoading = NO;
        [vc NSJSONReading];
    }];
    [self.myTableView headerBeginRefreshing];
}

- (void)addFooter{
    
     __block MovieListViewController *vc = self;
    
    
    [self.myTableView addFooterWithCallback:^{
        
        vc.isUpLoading = YES;
        [vc NSJSONReading];
    }];
}
   // 数据解析
- (void)NSJSONReading{
 
    NSMutableArray *a = [NSMutableArray array];
    NSMutableArray *array = [[DataBaseSingleton shareDataBase]selectMovie];
    for (Movie *movie in array) {
        [a addObject:movie.movieName];
    }
    self.allArray = [NSMutableArray arrayWithArray:array];
    self.array = [NSMutableArray array];
    NSLog(@"=====%@",self.allArray);
    
    [AppTools getMovieFromJsonWithfilmName:@"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/movielist.php" block:^(id result) {
        
        [self.allArray removeAllObjects];
        if (self.isUpLoading == 0) {
            [self.allArray removeAllObjects];
        }
        NSMutableDictionary *dic = result;
        NSMutableArray *array = [dic objectForKey:@"result"];
        NSLog(@"------%@",array);
        for (NSDictionary *dic in array) {
            
            Movie *movie = [[Movie alloc]init];
            
            [movie setValuesForKeysWithDictionary:dic];
            if (![a containsObject:movie.movieName]) {
                [[DataBaseSingleton shareDataBase]inserMovieIntoTable:movie];
            }
            
            [self.allArray addObject:movie];
            [self.array addObject:movie.movieName];
            
}
        
        [self.myTableView footerEndRefreshing];
        [self.myTableView headerEndRefreshing];
        [self.myTableView reloadData];
        
        
    } error:^(NSError *error) {
        [self.myTableView footerEndRefreshing];
        [self.myTableView headerEndRefreshing];
        [self.myTableView reloadData];

    }];
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    return 180;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    // 如果是活动状态,说明是当前正在搜索
    if (self.searchController.active) {
        
        return self.searchallArray.count;
        
    }else{
        
        return self.allArray.count;

    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdenTifier = CELL;
    MovieListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdenTifier];
    if (cell==nil) {
        
        cell = [[MovieListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdenTifier];
    }
    if (self.searchController.active) {
        
        NSMutableAttributedString *att = [[NSMutableAttributedString alloc]initWithString:[self.searchallArray objectAtIndex:indexPath.row]];
        
        [att addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[[self.searchallArray objectAtIndex:indexPath.row]rangeOfString:[self.searchController.searchBar text]]];
        cell.textLabel.attributedText = att;
    }
    else{
        
        cell.textLabel.attributedText = nil;
        
        Movie *aMovie = [self.allArray objectAtIndex:indexPath.row];
        
        cell.movie = aMovie;
 
    }
//    MovieListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL];
//    NSLog(@"%11111@",self.allArray);
    
    return cell;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
   // 取消置灰效果
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MovieDataViewController *movieDataView = [[MovieDataViewController alloc]init];
    if (self.searchController.active) {
        NSLog(@"选中搜索中");
        movieDataView.movie.movieName = [self.searchallArray objectAtIndex:indexPath.row];
        

    }
    else{
        
        NSLog(@"选中所有列表");
        movieDataView.movie.movieName = [self.array objectAtIndex:indexPath.row];
        
        
        
        
        
        
      }
    movieDataView.movie = [self.allArray objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:movieDataView animated:YES];

//    movieDataView.movie = [self.allArray objectAtIndex:indexPath.row];
    
}

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    
    NSString *searchString = [self.searchController.searchBar text];
    NSLog(@"===%@",searchString);
    
    NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@",searchString];
    if (self.searchallArray!=nil) {
        [self.searchallArray removeAllObjects];
    }
    NSLog(@"searchArray=%@",self.array);
    self.searchallArray = [NSMutableArray arrayWithArray:[self.array filteredArrayUsingPredicate:preicate]];
    
    NSLog(@"searchArray == %@",self.searchallArray);
    [self.myTableView reloadData];
}
- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    if (self.searchController.active) {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
